package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.system.domain.ApUser;
import com.ruoyi.system.mapper.ApUserMapper;
import com.ruoyi.system.service.ApUserService;
import com.ruoyi.system.util.RedisClient;
import com.ruoyi.system.util.ResponseResult;
import com.ruoyi.system.util.Result;
import com.ruoyi.system.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Service
public class ApUserServiceImpl implements ApUserService {
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private ApUserMapper apUserMapper;
    @Override
    public ResponseResult sendCode(Map<String, Object> map) {
        Object phone = map.get("phone");

        // 校验手机号是否为空
        if (phone == null || StringUtils.isBlank(phone.toString())) {
            return ResponseResult.errorResult(400, "手机号不能为空!");
        }

        // 将手机号转换为字符串
        String phoneStr = phone.toString();

        // 手机号格式校验，假设是中国大陆手机号
        String phoneRegex = "^1[3-9]\\d{9}$";
        if (!Pattern.matches(phoneRegex, phoneStr)) {
            return ResponseResult.errorResult(400, "手机号格式不正确!");
        }
        //生成验证码
        Integer integer = ValidateCodeUtils.generateValidateCode(4);

        Date date = new Date();
        SimpleDateFormat s = new SimpleDateFormat();
        String format = s.format(date);

        System.err.println(format+":手机号为{"+phone+"}的用户，您的验证码为:"+integer);
        redisClient.set((String) phone, integer);
        redisClient.expire((String) phone, 60);
        return ResponseResult.okResult(200, "验证码发送成功!" );
    }

    @Override
    public ResponseResult login(Map<String, Object> map) {
        Object phone = map.get("phone");//手机号
        Object password = map.get("password");//密码
        Object code = map.get("code");//验证码
        //参数校验 校验手机号
        if (phone == null || StringUtils.isBlank(phone.toString())) {
            return ResponseResult.errorResult(400, "手机号不能为空!");
        }
        // 手机号格式校验，假设是中国大陆手机号
        String phoneRegex = "^1[3-9]\\d{9}$";
        if (!Pattern.matches(phoneRegex, phone.toString())) {
            return ResponseResult.errorResult(400, "手机号格式不正确!");
        }
        // 校验验证码
        if (code == null || StringUtils.isBlank(code.toString())) {
            return ResponseResult.errorResult(400, "验证码不能为空!");
        }

        String phonex = (String) phone;
        Object o = redisClient.get(phonex);
        if(o == null){
            return ResponseResult.errorResult(400, "验证码已失效!");
        }

        // 验证码验证
        if (!o.toString().equals(code.toString())) {
            return ResponseResult.errorResult(400, "验证码不匹配!");
        }

        //判断是否用户存在
//        LambdaQueryWrapper<ApUser> lm = new LambdaQueryWrapper<>();
//        lm.eq(ApUser::getPhone, phone);
        List<ApUser> apUserList = apUserMapper.selectList(String.valueOf(phone));
        for (ApUser apUser : apUserList) {
            if(apUser == null){
                return ResponseResult.errorResult(400, "您还没注册,请前往注册!");
            }else{
                String token = UUID.randomUUID().toString();
                apUser.setToken(token);
                return ResponseResult.okResult(200, "登录成功!",apUser);
            }
        }
      return ResponseResult.errorResult(400, "您还没注册,请前往注册!");
    }

    @Override
    public Result register(ApUser user) {
        try {
            if(user != null){
                String phone = user.getPhone();
                List<ApUser> apUserList = apUserMapper.selectList(phone);
                for (ApUser apUser : apUserList) {
                    if(apUser == null){
                        apUserMapper.Apuserregist(user);
                        return Result.success(200, "注册成功!");
                    }else{
                        return Result.error(400, "您已经注册过了!");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
